package com.example.lenovo.asia5b.my.order.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.lenovo.asia5b.home.activity.HolidayDialogActivity;
import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.my.order.adapter.TheOrderAdapter;
import com.example.lenovo.asia5b.my.order.bean.TheOrderBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout;
import com.example.lenovo.asia5b.ui.PullToRefreshLayout.OnRefreshListener;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.MoneyUtil;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;


/**
 * Created by lenovo on 2017/6/21.
 */

public class TheOrderActvity extends BaseActivity implements OnRefreshListener, ICallBack, MoneyUtil.MoneyInterface{
    private ListView order_lv;
    private TheOrderAdapter adapter;
    private PullToRefreshLayout pullToRefreshLayout;

    private Button merpayorder, spepayorder;

    private LoadingDalog loadingDalog;

    public int page = 1;//页数
    private int countpage = 0;//总页数
    private int count = 1;//商品总数
    private List<TheOrderBean> theOrderBeanList;
    private   MoneyUtil moneyUtil = null;
    private PopupWindow pop;
    private String status = "",chajia,daiping;
    public boolean isSelect;

    private String merPayOrderStr;
    private String spePayOrderStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_the_order);
        initView();
        getPostAPI();
    }

    public void initView() {
        moneyUtil= new MoneyUtil(this);
        loadingDalog = new LoadingDalog(this);
        loadingDalog.show();
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.my_the_order));
        merpayorder = findViewById(R.id.activity_merpayorder);
        spepayorder = findViewById(R.id.activity_spepayorder);
        F.id(R.id.public_btn_left).clicked(this);
        F.id(R.id.public_txt_righe).visibility(View.VISIBLE);

        F.id(R.id.public_txt_righe).text("····");
        F.id(R.id.public_txt_righe).clicked(this);
//        F.id(R.id.item_the_order_payment).clicked(this);//付款

        order_lv = (ListView) findViewById(R.id.activity_order_lv);
        pullToRefreshLayout = ((PullToRefreshLayout) findViewById(R.id.refresh_view));
        pullToRefreshLayout.setOnRefreshListener(this);
        adapter = new TheOrderAdapter(this);

        order_lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (view.getLastVisiblePosition() == view.getCount() - 1) {
                        if (page <= countpage) {
                            page += 1;
                            getPostAPI();
                        } else {
                            TextView load_tv = (TextView) findViewById(R.id.load_tv);
                            load_tv.setText(getResources().getString(R.string.no_more_data));
                            load_tv.setVisibility(View.VISIBLE);
                        }
                    } else {
                    }
                }
            }
        });
        order_lv.setAdapter(adapter);

        if (getIntent().hasExtra("theOrder")) {
            F.id(R.id.public_txt_righe).visibility(View.GONE);
            String id = getIntent().getStringExtra("theOrder");
            status = id;
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.public_btn_left:
                if (isSelect) {
                    intent = new Intent();
                    intent.putExtra("222",2222);
                    this.setResult(0, intent);
                }
                finish();
                break;
            case R.id.txt_special:
                //特殊商品付款spePayOrderStr
                if (spePayOrderStr.equals("0")){
                    U.Toast(TheOrderActvity.this, getResources().getString(R.string.have_no_particularly_commodity_payment));
                    return;
                }
                intent = new Intent(TheOrderActvity.this,MergePaymentsActivity.class);
                intent.putExtra("type","1");
                startActivityForResult(intent,0);
                pop.dismiss();
                break;
            case R.id.txt_merge:
                //合并付款
                if (merPayOrderStr.equals("0")){
                    U.Toast(TheOrderActvity.this, getResources().getString(R.string.have_no_pay));
                }else{
                    intent = new Intent(TheOrderActvity.this,MergePaymentsActivity.class);
                    intent.putExtra("type","0");
                    startActivityForResult(intent,0);
                    pop.dismiss();
                }

                break;
            case  R.id.public_txt_righe:
                showPop();
                break;
            case R.id.txt_bcj:
                //补差价
                if (chajia.equals("0")){
                    U.Toast(TheOrderActvity.this, getResources().getString(R.string.have_no_buchajia));
                    return;
                }
                intent = new Intent(TheOrderActvity.this,TheOrderActvity.class);
                intent.putExtra("theOrder","13");
                startActivityForResult(intent,0);
                pop.dismiss();
                break;
            case R.id.txt_dpj:
                //待评价
                if (daiping.equals("0")){
                    U.Toast(TheOrderActvity.this, getResources().getString(R.string.have_no_dpj));
                    return;
                }
                intent = new Intent(TheOrderActvity.this,TheOrderActvity.class);
                intent.putExtra("theOrder","10");
                startActivityForResult(intent,0);
                pop.dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        page = 1;
        loadingDalog.show();
        getPostAPI();
    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                    pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 调用接口
     */
    public void getPostAPI() {
        try {
            Date date = new Date();
            UserBean userBean = (UserBean) SharedPreferencesUtils.getObjectFromShare("user");
            if (userBean != null) {
                String url = Setting.ORDERLIST;
                Map<String, String> map = new HashMap<String, String>();
                map.put("user_id", userBean.user_id);
                map.put("page", String.valueOf(page));
                map.put("time", String.valueOf(date.getTime()));

                //排序
                String[] sortStr = {"user_id" + userBean.user_id, "page" + page, "time" + date.getTime()};
                String sort = Logic.sortToString(sortStr);
                String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sort));
                map.put("sign", md5);
                map.put("status", status);
                JsonTools.getJsonAll(this, url, map, 0);
            }
        } catch (Exception e) {
            Log.e("我的订单error：", e.getMessage());
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            try {
                if (result != null) {
                    if (action == 0) {
                        JSONObject jsonObject = (JSONObject) result;
                        int state = jsonObject.getInt("State");
                        if (state == 0) {
                        /*begin 页数、上屏总数量 **/
                            JSONObject paging = jsonObject.getJSONObject("paging");
                            countpage = Integer.parseInt(paging.getString("countpage"));
                            count = Integer.parseInt(paging.getString("count"));
                        /*end 页数、上屏总数量 **/
                         /*begin 合并付款、特殊商品 按钮显示的提示信息 **/
                            JSONObject payOrder = jsonObject.getJSONObject("payOrder");
                            //合并付款
                            merPayOrderStr = payOrder.getString("merPayOrder");
                            isShow = false;
                            if (Integer.parseInt(merPayOrderStr) >= 10) {
                                merPayOrderStr = merPayOrderStr + "+";
                            }
                            if (!merPayOrderStr.equals("0")) {
                                F.id(R.id.txt_merge).clicked(TheOrderActvity.this);
                                merpayorder.setVisibility(View.VISIBLE);
                                isShow = true;
                            } else {
                                merpayorder.setVisibility(View.GONE);
                            }
                            merpayorder.setText(merPayOrderStr);
                            //特殊商品
                            spePayOrderStr = payOrder.getString("spePayOrder");
                            if (Integer.parseInt(spePayOrderStr) >= 10) {
                                spePayOrderStr = spePayOrderStr + "+";
                            }
                            if (!spePayOrderStr.equals("0")) {
                                F.id(R.id.txt_special).clicked(TheOrderActvity.this);
                                spepayorder.setVisibility(View.VISIBLE);
                                isShow = true;
                            } else {
                                spepayorder.setVisibility(View.GONE);
                            }
                            spepayorder.setText(spePayOrderStr);

                            chajia = payOrder.getString("chajia");
                            if (!chajia.equals("0")){
                                isShow = true;
                            }
                            daiping = payOrder.getString("daiping");
                            if (!daiping.equals("0")){
                                isShow = true;
                            }
                            /*end 合并付款、特殊商品 按钮显示的提示信息 **/
                            if (page == 1) {
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                initPaging(paging);
                            /*begin 订单列表 **/
                                JSONArray jsonArray = jsonObject.getJSONArray("order");
                                theOrderBeanList = Logic.getListToBean(jsonArray, new TheOrderBean());
                                adapter.setList(theOrderBeanList);
                                adapter.notifyDataSetChanged();
                            /*end 订单列表 **/
                            } else if (page != 1) {
                                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                                JSONArray jsonArray = jsonObject.getJSONArray("order");
                                List<TheOrderBean> newTheOrderBeanList = Logic.getListToBean(jsonArray, new TheOrderBean());
                                for (TheOrderBean order : newTheOrderBeanList) {
                                    theOrderBeanList.add(order);
                                }
                                adapter.setList(theOrderBeanList);
                                adapter.notifyDataSetChanged();
                            } else {
                                page = page - 1;
                            }
                            //是否显示红点
                            if (!isShow) {
                                F.id(R.id.txt_mess).visibility(View.GONE);
                            } else {
                                if (TextUtils.isEmpty(status)) {
                                    F.id(R.id.txt_mess).visibility(View.VISIBLE);
                                } else {
                                    F.id(R.id.txt_mess).visibility(View.GONE);
                                }
                            }
                        }else if (state == 1) {
                            U.Toast(TheOrderActvity.this, getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(TheOrderActvity.this, getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(TheOrderActvity.this, getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(TheOrderActvity.this, getResources().getString(R.string.mysj));
                        }
                    }
                }
            } catch (Exception e) {
                Log.e("我的订单JSONError:", e.getMessage());
            }
            loadingDalog.dismiss();
            pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
        }
    };

    /**
     * 接口回调
     * @param result
     * @param action
     */
    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    public void initPaging(JSONObject json) throws JSONException {
        String pageSizeString = json.getString("count");
        String countPageString = json.getString("countpage");
        String pageString = json.getString("page");
        if (pageSizeString != null && countPageString != null && pageString != null) {
            countpage = Integer.parseInt(countPageString);
            if (countpage <=1) {
                pullToRefreshLayout.stopLoadMore();
            }
        }
    }

    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                if (null != adapter){
                    adapter.clear();
                }
                isSelect= true;
                page = 1;
                loadingDalog.show();
                getPostAPI();
                moneyUtil.moneyData();
                if (data.hasExtra("confirm")) {
                    if (!HolidayDialogActivity.getOnes()) {
                        Intent intent = new Intent(TheOrderActvity.this,HolidayDialogActivity.class);
                        startActivity(intent);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void money(String user_money,String pay_points) {
    }
    //当合并付款和特殊商品付款都为0的时候，就设为 false
    private boolean isShow;

    public void showPop() {
        if (!isShow) {
            return;
        }
        int screenWidth = DensityUtil.getScreenHeight(TheOrderActvity.this);
        View popview = View.inflate(this, R.layout.view_the_order_right, null);
        TextView txt_merge = (TextView) popview.findViewById(R.id.txt_merge);
        txt_merge.setOnClickListener(this);
        TextView txt_special = (TextView) popview.findViewById(R.id.txt_special);
        txt_special.setOnClickListener(this);
        TextView txt_bcj = (TextView) popview.findViewById(R.id.txt_bcj);
        txt_bcj.setOnClickListener(this);
        TextView txt_dpl = (TextView) popview.findViewById(R.id.txt_dpj);
        txt_dpl.setOnClickListener(this);
            if (merpayorder.getVisibility() == View.VISIBLE) {
                txt_merge.setText(getResources().getString(R.string.integration_payment)+"("+merpayorder.getText().toString()+")");
            } else {
                txt_merge.setText(getResources().getString(R.string.integration_payment)+"(0)");
            }
            if (spepayorder.getVisibility() == View.VISIBLE) {

                txt_special.setText(getResources().getString(R.string.particularly_commodity_payment)+"("+spepayorder.getText().toString()+")");
            } else {
                txt_special.setText(getResources().getString(R.string.particularly_commodity_payment)+"(0)");
            }
            if (!chajia.equals("0")) {
                txt_bcj.setText(getResources().getString(R.string.bcj)+"("+chajia+")");
            } else {
                txt_bcj.setText(getResources().getString(R.string.bcj)+"(0)");
            }
            if (!daiping.equals("0")) {
                txt_dpl.setText(getResources().getString(R.string.dpj)+"("+daiping+")");
            } else {
                txt_dpl.setText(getResources().getString(R.string.dpj)+"(0)");
            }

            pop = new PopupWindow(popview,FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, true);
            pop.setBackgroundDrawable(new BitmapDrawable());
            pop.setWidth(DensityUtil.dip2px(TheOrderActvity.this,200));
            pop.setOutsideTouchable(true);
        pop.showAsDropDown(findViewById(R.id.public_txt_righe),screenWidth,0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击的是返回键
        if(keyCode == KeyEvent.KEYCODE_BACK){
                if (isSelect) {
                Intent intent = new Intent();
                intent.putExtra("222",2222);
                this.setResult(0, intent);
            }
            finish();

        }
        return false;
    }
}